package com.algorithm.other;

/**
 * @author: tzj
 * @create: 2022-10-11
 * 二分查找法，采用左闭右闭区间解法->[]
 **/
public class Search_704 {

    public static void main(String[] args) {
        int[] nums = {-1, 0, 3, 5, 9, 12};
        int target = 2;
        System.out.println(search(nums, target));
    }

    public static int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        // 左闭右闭解法两边是可以相等
        while (left <= right) {
            int middle = (left + right) / 2;
            if (target < nums[middle]) {
                // 此时右边界不满足，应排除
                right = middle - 1;
            } else if (target > nums[middle]) {
                // 此时左边界不满足，应排除
                left = middle + 1;
            } else {
                return middle;
            }
        }
        return -1;
    }
}
